package com.example.swagger.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 只要是配置类一定要添加这个注解，防止重复创建对象
 */
@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDatasource() {
        return new DruidDataSource();
    }

    //后台监控:web.xml
//    @Bean
    public ServletRegistrationBean statViweServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet());

        //后台需要有人登录，账号密码设置，
        //因为springboot内置了servlet，所以没有web.xml,替代方法ServletRegistrationBean
        HashMap<String,String> initParameters = new HashMap<>();
//增加配置
        initParameters.put("loginUsername","admin");//登录key是固定的，loginUsername，loginPassword
        initParameters.put("loginPassword","123456");

        //允许谁可以访问
        initParameters.put("allow","localhost");

        //禁止谁访问
//        initParameters.put("xxx","");

        bean.setInitParameters(initParameters);//设置初始化参数
        return bean;
    }

    //filter
    public FilterRegistrationBean webstatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        //可以过滤哪些请求呢？
        Map<String,String> initParameters = new HashMap<>();

        initParameters.put("exclusion","*.js,*.css,/druid/*");

        bean.setInitParameters(initParameters);
        return bean;
    }
}
